import React from 'react';
import {Card, Form, Input, InputNumber, message, Select, Table, DatePicker} from 'antd';
import SearchForm from '../../components/AutoForm/SearchForm';
import {connect} from 'dva';
import moment from 'moment';
import EditForm from "../../components/AutoForm/EditForm";
import locale from 'antd/es/date-picker/locale/zh_CN'

const EditableContext = React.createContext();

@connect(({ dispatchOrder, loading }) => ({
  tableLoading: loading.effects['dispatchOrder/orderPage'],
  tableData: dispatchOrder.childrenTable,
}))
class chlidrenTable extends React.Component {
  render() {
    return super.render();
  }
}

@connect(({ dispatchOrder }) => ({
  requiredCols: dispatchOrder.requiredCols,
}))
class EditableCell extends React.Component {
  getInput = dataIndex => {
    switch (dataIndex) {
      case 'avgFlag':
        return (
          <Select style={{ width: 70 }}>
            <Option value="V">体积</Option>
            <Option value="W">重量</Option>
            <Option value="Z">整车</Option>
          </Select>
        );
      case 'pickFee':
        return <InputNumber />;
      case 'arteryFee':
        return <InputNumber />;
      case 'dropoffFee':
        return <InputNumber />;
      case 'workoverFee':
        return <InputNumber />;
      case 'loadupFee':
        return <InputNumber />;
      case 'loadoffFee':
        return <InputNumber />;
      case 'carFee':
        return <InputNumber />;
      case 'fuelFee':
        return <InputNumber />;
      case 'callbackFee':
        return <InputNumber />;
      case 'escortinFee':
        return <InputNumber />;
      case 'tipFee':
        return <InputNumber />;
      case 'shuttleFee':
        return <InputNumber />;
      default:
        return <Input />;
    }
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      requiredCols,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, padding: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: requiredCols[title],
              initialValue: record[dataIndex],
            })(this.getInput(dataIndex))}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({ dispatchOrder, loading }) => ({
  tableLoadingC: loading.effects['dispatchOrder/orderPage'],
  tableDataC: dispatchOrder.childrenTable,
  columnsC: dispatchOrder.columnsChlidren,

  tableLoading: loading.effects['dispatchOrder/page'],
  formLoading: loading.effects['dispatchOrder/save', 'dispatchOrder/applyPay'],
  tableData: dispatchOrder.pageList,
  pagination: dispatchOrder.pagination,
  columns: dispatchOrder.columns,
  searchFields: dispatchOrder.searchFields,
  searchValues: dispatchOrder.searchValues,
  editId: dispatchOrder.editId,
  selectionIds: dispatchOrder.selectionIds,
  selectedRows: dispatchOrder.selectedRows,
  moneyModal: dispatchOrder.moneyModal,
  modalForm: dispatchOrder.modalForm,
  moneyRows: dispatchOrder.moneyRows,
  selectionOrderIds: dispatchOrder.selectionOrderIds,
}))
class EditableTable extends React.Component {

  state = {
    sumText: '选中合计费用：0',
    applyForm: {
      applyPayTime: {
        name: 'applyPayTime',
        value: moment()
      }
    },
    applyModal: false,
    applyRows: [
      {
        cols: [
          {
            label: '支付时间',
            name: 'applyPayTime',
            md: 12,
            rules: [{ required: true, message: ' ' }],
            component: <DatePicker locale={locale} showTime format="YYYY-MM-DD HH:mm:ss" placeholder="请输入支付时间" />,
          },
        ],
      },]
  };

  componentDidMount() {
    this.handleSearch();
  }

  expandedRowRender = record => {
    const { columnsC } = this.props;
    return <Table size="small" columns={columnsC} dataSource={record.orders} pagination={false} />;
  };
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dispatchOrder/handleEdit',
      payload: '',
    });
  };

 /* save(form) {
    const { dispatch, selectedRows } = this.props;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      dispatch({
        type: 'dispatchOrder/save',
        payload: { ...row, ...record },
      }).then(() => {
        this.handleSearch();
      });
    });
  }*/

  handleEdit(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'dispatchOrder/handleEdit',
      payload: key,
    });
  }

  handleSearchChange = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dispatchOrder/handleSearchChange',
      payload: fields,
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dispatchOrder/handleAdd',
    });
  };
  handleApplyChange = field => {
    this.setState({
      applyForm: field
    })
  }
  handleModalChange = fields => {
    const { dispatch, optFlag, addForm } = this.props;
    const payload = { fields: fields, optFlag: optFlag, addForm: addForm };
    dispatch({
      type: 'dispatchOrder/handleModalChange',
      payload: payload,
    });
  };

  handleApplyVisble = () => {
    this.setState({
      applyModal: false
    })
  }

  handleModalVisible = () => {
    const { dispatch, modalForm } = this.props;
    dispatch({
      type: 'dispatchOrder/handleMoneyModal',
      payload: {
        moneyModal: false,
        modalForm: modalForm
      }
    });
  };

  handleCostSub = fields => {
    const { dispatch, selectedRows, } = this.props;

    const params = {
      ...selectedRows[0],
      ...fields
    };

    dispatch({
      type: 'dispatchOrder/save',
      payload: params
    }).then(() => {
      this.handleSearch();
      this.handleModalVisible();
    });
  };


  handleSearch = (flag) => {
    const { dispatch, pagination, searchValues } = this.props;
    let pageParam = { pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current };
    let searchParam = {};
    Object.keys(searchValues).map(key => {
      searchParam[key] = searchValues[key]['value'];
    });
    const param = {
      ...searchParam,
      ...pageParam,
    };
    dispatch({
      type: 'dispatchOrder/page',
      payload: param,
    });
  };

  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;let sum = 0.0;
    selectedRows.forEach(row => {
      sum += row.feeSum;
    });
    this.setState({ sumText: `选中合计费用：${sum}` });
    dispatch({
      type: 'dispatchOrder/handleSelection',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  onDel = () => {
    const { dispatch, selectedRows } = this.props;
    if (!selectedRows.length) {
      return message.error('请选择一行要删除的数据');
    }
    const { status } = selectedRows[0];
    if (status !== 'ENTRY') {
      return message.error('状态异常');
    }
    dispatch({
      type: 'dispatchOrder/del',
      payload: selectedRows[0],
    }).then(() => {
      this.handleSearch();
    });
  };

  onModal = () => {
    const { dispatch, selectedRows, modalForm } = this.props;
    if(selectedRows.length !== 1){
      return message.error('请选择一行要修改的数据');
    }
    const costOrder = selectedRows[0];
    let isShow = true;
    costOrder.orders.forEach(order => {
      if(order.status === 'RECEIPT' || order.status === 'INVOICE_HALF' || order.status === 'INVOICE' || order.status === 'GATHERING' || order.status === 'FINISH'){
        isShow = false;
      }
    })
    if(!isShow){
      return message.error('订单状态异常')
    }
    /*if(costOrder.status === 'PAY' || costOrder.status === 'PAY_FINISH'){
      return message.error('费用状态异常')
    }*/
    if(costOrder.status !== 'ENTRY'){
      return message.error('费用状态异常')
    }
    let newModalForm = modalForm
    if(costOrder){
      Object.keys(costOrder).forEach(k => {
        if(k !== 'orders'){
          newModalForm[k] = {
            name: k,
            value: costOrder[k]
          }
        }
      })
    }else{
      newModalForm = modalForm
    }
    dispatch({
      type: 'driver/selectList',
      payload: {driver: costOrder.driver}
    }).then(()=> {
      dispatch({
        type: 'dispatchOrder/handleMoneyModal',
        payload: {
          moneyModal: true,
          modalForm: newModalForm
        }
      });
    })
  }

  onUrgent = () => {
    const { dispatch, selectedRows, } = this.props;
    if(selectedRows.length !== 1){
      return message.error('请选择一行要修改的数据');
    }
    const costOrder = selectedRows[0];
    costOrder.orders.forEach(order => {
      if(order.status === 'RECEIPT' || order.status === 'INVOICE' || order.status === 'GATHERING' || order.status === 'FINISH'){
        return message.error('状态异常')
      }
    })
    const params = {
      ...selectedRows[0],
    };

    dispatch({
      type: 'dispatchOrder/urgentCost',
      payload: params
    }).then(() => {
      this.handleSearch();
    });


  }

  onPay = () => {
    const { dispatch, selectedRows } = this.props;
    if (!selectedRows.length) {
      return message.error('请选择一行要申请的数据');
    }
    const { status } = selectedRows[0];
    if (status !== 'PASS') {
      return message.error('状态异常');
    }
    const applyPayTime = this.state.applyForm.applyPayTime.value.add(8, 'h')
    selectedRows.forEach(row=>{
      row.applyPayTime = applyPayTime
    })
    dispatch({
      type: 'dispatchOrder/applyPay',
      payload: selectedRows,
    }).then(() => {
      this.handleApplyVisble()
      this.handleSearch();
    });
  };

  onPayShow = () => {
    debugger
    const { selectedRows } = this.props;
    if (!selectedRows.length) {
      return message.error('请选择一行要申请的数据');
    }
    const { status } = selectedRows[0];
    if (status !== 'PASS') {
      return message.error('状态异常');
    }
    this.setState({
      applyModal: true
    })
  }

  onSend = () => {
    const { dispatch, selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一行要删除的数据');
    }
    const { status } = selectedRows[0];
    if (status !== 'ENTRY') {
      return message.error('状态异常');
    }
    dispatch({
      type: 'dispatchOrder/apply',
      payload: selectedRows[0],
    }).then(() => {
      this.handleSearch();
    });
  };


  render() {
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      searchFields,
      searchValues,
      editId,
      moneyRows,
      modalForm,
      moneyModal,
      formLoading,
      dispatch,
    } = this.props;
    const components = {
      body: {
        cell: EditableCell,
      },
    };
    const optColumns = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: editId === record.id,
        }),
      };
    });
  /*  optColumns.push({
      title: '操作',
      width: '120px',
      fixed: 'right',
      render: (text, record) => {
        const editable = editId === record.id;
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <a
                  onClick={() => this.save(form, { id: record.id, loadNo: record.loadNo })}
                  style={{ marginRight: 8 }}
                >
                  保存
                </a>
              )}
            </EditableContext.Consumer>
            <Popconfirm
              title="确认取消?"
              cancelText="取消"
              okText="确定"
              onConfirm={() => this.cancel(record.id)}
            >
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <a
            disabled={editId !== '' || record.status !== 'ENTRY'}
            onClick={() => this.handleEdit(record.id)}
          >
            编辑
          </a>
        );
      },
    });*/

    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'dispatchOrder/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize,
        },
      });
    };
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'dispatchOrder/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size,
        },
      });
    };

    const rowSelection = {
      type: 'checkbox',
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange,
      /*getCheckboxProps: record => ({
        disabled: record.status !== 'ENTRY'
      })*/
    };

    return (
      <Card bodyStyle={{ padding: 0 }}>
        <SearchForm
          header="运调->操作"
          moneyText="申请支付"
          layout="inline"
          onFieldsChange={this.handleSearchChange}
          isAdd={false}
          isDel={true}
          isPay={true}
          isEdit={true}
          isSum={true}
          sumText={this.state.sumText}
          /* isUrgent={true}*/
          onModal={this.onModal}
          onAdd={this.handleAdd}
          onSend={this.onSend}
          onSubmit={() => {this.handleSearch('btn')}}
          onDel={this.onDel}
          onPay={this.onPayShow}
          /*onUrgent={this.onUrgent}*/
          isSend={true}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <EditableContext.Provider value={this.props.form}>
          <Table
            /*defaultExpandAllRows={true}*/
            components={components}
            bordered
            rowKey="id"
            loading={tableLoading}
            dataSource={tableData}
            columns={optColumns}
            rowSelection={rowSelection}
            rowClassName="editable-row"
            scroll={{ x: 'max-content' }}
            size="small"
            pagination={pagination}
            expandedRowRender={this.expandedRowRender}
          />
        </EditableContext.Provider>
        <EditForm
          title="修改费用"
          rows={moneyRows}
          fieldValue={modalForm}
          onFieldsChange={this.handleModalChange}
          onCancel={this.handleModalVisible}
          onOk={this.handleCostSub}
          confirmLoading={formLoading}
          visible={moneyModal}
        />
        <EditForm
          title="申请费用"
          rows={this.state.applyRows}
          fieldValue={this.state.applyForm}
          onFieldsChange={this.handleApplyChange}
          onCancel={this.handleApplyVisble}
          onOk={this.onPay}
          confirmLoading={formLoading}
          visible={this.state.applyModal}
        />

        {/*<EditForm
          title="紧急费用"
          rows={moneyRows}
          fieldValue={modalForm}
          onFieldsChange={this.handleModalChange}
          onCancel={this.handleModalVisible}
          onOk={this.handleUrgentSub}
          confirmLoading={formLoading}
          visible={moneyModal}
        />*/}
      </Card>
    );
  }
}

const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
